package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    /**
     * 保存套餐和关系表数据
     *
     * @param setmealDto
     */
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //1. 保存套餐
        save(setmealDto);

        //2. 保存套餐和菜品关系表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            // 设置分类id
            setmealDish.setSetmealId(setmealDto.getId());
        });

        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐 和 套餐菜品关系表
     *
     * @param ids
     */
    @Override
    @Transactional
    public void removeByDish(List<Long> ids) {

        //1. 删除套餐
        // select * from setmeal where id in(?,?,?) and status = 1
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getStatus, 1); // 1 起售
        lqw.in(Setmeal::getId, ids);
        int count = count(lqw);

        if (count > 0) {
            throw new CustomException("套餐正在售卖中,不能删除");
        }
        removeByIds(ids);

        //2. 删除关系表
        // delete from setmeal_dish where setmeal_id in (?,?,?)
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lambdaQueryWrapper);
    }
}
